#include <SoftwareSerial.h>
#include "sensor.h"
#include "relay.h"
#include "controller.h"
#include "gsm.h"
#include "settings.h"
#include "TR.h"
#include "COSM.h"
#include "perimeter.h"
#include "freememory.h"

Sensor sensor1(A0);
Sensor sensor2(A1);

GSM gsm(PHONE_NUMBER);

Relay relay1(2);
Relay relay2(3);

TR tr1("C1", sensor1, relay1);
TR tr2("C2", sensor2, relay2);

COSM cosm(gsm, tr1, tr2);

Perimeter perimeter(4);

FreeMemory freeMem;

#define CONTROLLER_COUNT 5
Controller *controllers[CONTROLLER_COUNT];

boolean sendStatusSms;


void setup()
{
  Serial.begin(19200);

  gsm.power();
  gsm.init();

  sensor1.init();
  sensor2.init();

  sendStatusSms = true;

  controllers[0] = &tr1;
  controllers[1] = &tr2;
  controllers[2] = &cosm;
  controllers[3] = &perimeter;
  controllers[4] = &freeMem;
}


void loop()
{

  sendStatusSms = gsm.check() || sendStatusSms;
  
  String inSms = gsm.receiveSMS();
  inSms.toLowerCase();

  if(inSms != "") {

    Serial.println("IN SMS:" + inSms);

  }


  if(inSms == "get") {

    sendStatusSms = true;

  }
  else if(inSms.startsWith("set")) {

    sendStatusSms = true;

    // remove leading 'set'
    inSms = inSms.substring(3);
    inSms.trim();


    while(inSms != "") {

      int i = inSms.indexOf(" ");
      String cmd;
      if(i >= 0) {
        cmd = inSms.substring(0, i);
        inSms = inSms.substring(i + 1);
      } 
      else {
        cmd = inSms;
        inSms = "";
      }

      Serial.println("CMD:'" + cmd + "'");

      i = cmd.indexOf("=");
      if(i>0) {
        String ctrlId = cmd.substring(0, i);
        String param = cmd.substring(i + 1);
        for(int c = 0 ; c < CONTROLLER_COUNT ; c++) {
          if(ctrlId.equalsIgnoreCase(controllers[c]->getId())) {
            controllers[c]->setCommand(param);
          }   
        }
      }
    }
  }

  for(int c = 0 ; c < CONTROLLER_COUNT ; c++) {
    if(controllers[c]->check()) {
      sendStatusSms = true;
    }
  }

  if(sendStatusSms) {

    String outSms = "";
    for(int c = 0 ; c < CONTROLLER_COUNT ; c++) {
      outSms = outSms + " " + controllers[c]->getStatus();
    }

    Serial.println("OUT SMS:" + outSms);

    sendStatusSms = !gsm.sendSMS(outSms);

  }

}


